package com.jdew.thkj.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.adapter.JDCollectionAdapter;
import com.jdew.thkj.adapter.MyAdapter;
import com.jdew.thkj.adapter.PddCollectionAdapter;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.CollectionBean;
import com.jdew.thkj.bean.PddCollectionBean;
import com.jdew.thkj.bean.TbCollectionBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.swipeview.ISwipeMenuCreator;
import com.jdew.thkj.swipeview.SwipeMenu;
import com.jdew.thkj.swipeview.SwipeMenuItem;
import com.jdew.thkj.swipeview.SwipeMenuListView;
import com.jdew.thkj.utils.HankkinUtil;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/11/29.
 */

public class ShouCangActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.swipe)
    SwipeMenuListView swipeMenuListView;
    @Bind(R.id.resultclick)
    TextView resultclick;
    @Bind(R.id.noresult)
    LinearLayout noresult;
    @Bind(R.id.tablayout)
    TabLayout tablayout;
    @Bind(R.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private List<TbCollectionBean.DataBean> list = new ArrayList<>();
    private List<PddCollectionBean.DataBean> list2 = new ArrayList<>();
    private MyAdapter adapter;
    private PddCollectionAdapter adapter2;
    private JDCollectionAdapter adapter3;
    private String itemId;
    private String url;
    private String quan;
    private Dialog mWeiboDialog;
    private int sourceType = 0;
    private int page = 1;

    @Override
    public int bindLayout() {
        return R.layout.activity_shoucang;
    }

    @Override
    public void initView(View view) {
        title.setText("我的收藏");
        back.setVisibility(View.VISIBLE);
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        tablayout.post(new Runnable() {
            @Override
            public void run() {
                setIndicator(tablayout, 30, 30);
            }
        });
        tablayout.addTab(tablayout.newTab().setText("淘宝天猫"));
        tablayout.addTab(tablayout.newTab().setText("拼多多"));
        tablayout.addTab(tablayout.newTab().setText("京东"));
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    sourceType = 0;
                    smartRefreshLayout.setEnableRefresh(true);
                    smartRefreshLayout.setEnableLoadMore(true);
                    getCollection();
                } else if (tab.getPosition() == 1) {
                    sourceType = 1;
                    smartRefreshLayout.setEnableRefresh(false);
                    smartRefreshLayout.setEnableLoadMore(false);
                    getPddCollection();
                } else {
                    sourceType = 2;
                    smartRefreshLayout.setEnableRefresh(false);
                    smartRefreshLayout.setEnableLoadMore(false);
                    getJDCollection();
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        adapter = new MyAdapter(this, list);
        adapter2 = new PddCollectionAdapter(this, list2);
        adapter3 = new JDCollectionAdapter(this, list2);
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        TextView textView = new TextView(ShouCangActivity.this);
        textView.setMinimumWidth(width);
        textView.setText("无更多数据");
        textView.setPadding(0, 20, 0, 20);
        textView.setGravity(Gravity.CENTER);
        swipeMenuListView.addFooterView(textView);
        swipeMenuListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (sourceType == 0) {
                    if (position == list.size()) {
                        return;
                    }
                } else if (sourceType == 0) {
                    if (position == list2.size()) {
                        return;
                    }
                } else {
                    if (position == list2.size()) {
                        return;
                    }
                }
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (sp.getString("SpareTwo", "").equals("")) {
                    startActivity(new Intent(ShouCangActivity.this, LoginActivity.class));
                } else if (sp.getString("UserSjPhone", "").equals("") && (!sp.getString("SpareTwo", "").equals("1"))) {
                    toset("检测到您还没有绑定上级,请到我的页面绑定上级");
                } else {
                    if (sourceType == 0) {
                        itemId = list.get(position).getItemId();
                    } else if (sourceType == 1) {
                        itemId = list2.get(position).getGoodsid();
                    } else {
                        itemId = list2.get(position).getItemId();
                    }
                    Bundle b = new Bundle();
                    b.putSerializable("itemId", itemId);
                    b.putString("url", url);
                    b.putString("quan", quan);
                    if (sourceType == 0) {
                        startActivity(TbProductDetailActivity.class, b);
                    } else if (sourceType == 1) {
                        startActivity(PddDetailActivity.class, b);
                    } else {
                        startActivity(JDProductDetailActivity.class, b);
                    }
                }
            }
        });
        smartRefreshLayout.setRefreshHeader(new MaterialHeader(this));
        smartRefreshLayout.setRefreshFooter(new BallPulseFooter(this));
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                if (sourceType == 0) {
                    getCollection();
                }
            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                if (sourceType == 0) {
                    getCollection();
                }
            }
        });
        back.setOnClickListener(this);
        resultclick.setOnClickListener(this);
        swipeMenuListView.setMenuCreator(creator);
        swipeMenuListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                String id = null;
                if (sourceType == 0) {
                    id = list.get(position).getItemId();
                    CanceltheCollection(id, position);
                } else if (sourceType == 1) {
                    id = list2.get(position).getGoodsid();
                    CancelthePddCollection(id, position);
                } else {
                    id = list2.get(position).getItemId();
                    CanceltheJDCollection(id, position);
                }
            }
        });
    }

    ISwipeMenuCreator creator = new ISwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
            // 创建滑动选项
            SwipeMenuItem showItem = new SwipeMenuItem(
                    getApplicationContext());
            // 设置选项背景
            showItem.setBackground(new ColorDrawable(Color.rgb(0xC9, 0xC9,
                    0xCE)));
            SwipeMenuItem deleteItem = new SwipeMenuItem(
                    getApplicationContext());
            deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                    0x3F, 0x25)));
            deleteItem.setWidth(HankkinUtil.dp2px(90, ShouCangActivity.this));
            deleteItem.setIcon(R.mipmap.ic_delete);
            menu.addMenuItem(deleteItem);
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.resultclick: {
                getCollection();
                if (list.size() == 0) {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("没有更多收藏");
                }
            }
            break;
            default:
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (sourceType == 0) {
            getCollection();
        } else if (sourceType == 1) {
            getPddCollection();
        } else if (sourceType == 2) {
            getJDCollection();
        }
    }

    public void getCollection() {
        swipeMenuListView.setAdapter(adapter);
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetCollectionList(userName, page, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "PageIndex" + page + "UserName" + userName)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<TbCollectionBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(TbCollectionBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                smartRefreshLayout.finishLoadMore();
                smartRefreshLayout.finishRefresh();
                if (bean.getCode().equals("0")) {
                    if (null == bean.getData()) {
                        return;
                    }
                    if (page == 1) {
                        list.clear();
                        adapter.setDataList(list);
                    }
                    list.addAll(bean.getData());
                    adapter.setDataList(list);
                    if (list.size() % 20 != 0) {
                        smartRefreshLayout.setEnableLoadMore(false);
                    }
                    if(page>1){
                        swipeMenuListView.setSelection((page-1)*20-1);
                    }
                }
            }
        });
    }

    public void getPddCollection() {
        swipeMenuListView.setAdapter(adapter2);
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).PDDGetcollection(userName, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + userName)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<PddCollectionBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(PddCollectionBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    if (null != bean.getData()) {
                        list2.clear();
                        list2.addAll(bean.getData());
                        adapter2.setDataList(list2);
                    } else {
                        noresult.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    public void getJDCollection() {
        swipeMenuListView.setAdapter(adapter3);
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String userId = sp.getString("userId", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).JdGetcollection(userId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserId" + userId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<PddCollectionBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(PddCollectionBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    if (null != bean.getData()) {
                        list2.clear();
                        list2.addAll(bean.getData());
                        adapter3.setDataList(list2);
                    } else {
                        noresult.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    public void CanceltheCollection(String id, final int position) {
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).CanceltheCollection(userName, id, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserName" + userName + "ItemId" + id)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(ShouCangActivity.this).showMessage(e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("删除成功");
                    list.remove(position);
                    adapter.setDataList(list);
                    if (list.size() == 0) {
                        noresult.setVisibility(View.VISIBLE);
                    } else {
                        noresult.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("删除失败");
                }
            }
        });
    }

    public void CancelthePddCollection(String id, final int position) {
        String userName = sp.getString("userPhone", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).PDDCanceltheCollection(userName, id, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + userName + "Goodsid" + id)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(ShouCangActivity.this).showMessage(e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("删除成功");
                    list2.remove(position);
                    adapter2.setDataList(list2);
                    if (list2.size() == 0) {
                        noresult.setVisibility(View.VISIBLE);
                    } else {
                        noresult.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("删除失败");
                }
            }
        });
    }

    public void CanceltheJDCollection(String id, final int position) {
        String userId = sp.getString("userId", "");
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).JdCanceltheCollection(userId, id, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserId" + userId + "Goodsid" + id)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(ShouCangActivity.this).showMessage(e.toString());
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("删除成功");
                    list2.remove(position);
                    adapter3.setDataList(list2);
                    if (list2.size() == 0) {
                        noresult.setVisibility(View.VISIBLE);
                    } else {
                        noresult.setVisibility(View.GONE);
                    }
                } else {
                    ToastUtils.getInstance(ShouCangActivity.this).showMessage("删除失败");
                }
            }
        });
    }

    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }
}
